﻿using Application.Common.Interfaces;
using Common.Attributes;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Application.Features.Organizations.Commands.Delete;

#nullable disable

/// <summary>
/// 删除组织机构
/// </summary>
[Description("删除")]
[GroupDescription("组织机构")]
public class DeleteOrganizationCommand : IRequest<bool>
{
    /// <summary>
    /// 删除组织机构的唯一标识
    /// </summary>
    [Required(ErrorMessage = "删除数据的唯一标识是必填的")]
    public long OrganizationId { get; set; }
}

/// <summary>
/// 处理程序
/// </summary>
public class DeleteOrganizationCommandHandler : IRequestHandler<DeleteOrganizationCommand, bool>
{
    private readonly IApplicationDbContext _context;

    public DeleteOrganizationCommandHandler(
        IApplicationDbContext context)
    {
        _context = context;
    }

    /// <summary>
    /// 业务逻辑
    /// </summary>
    /// <param name="request">请求参数</param>
    /// <param name="cancellationToken">取消标记</param>
    /// <returns>返回处理结果</returns>
    public async Task<bool> Handle(DeleteOrganizationCommand request, CancellationToken cancellationToken)
    {
        var organizationToDelete = await _context.Organizations.SingleOrDefaultAsync(x => x.Id == request.OrganizationId);
        _context.Organizations.Remove(organizationToDelete);

        return true;
    }
}